using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using UniversalAdmin.Application.DTOs;
using UniversalAdmin.Application.Services;

namespace UniversalAdmin.Api.Controllers;

[ApiController]
[Route("api/v1/[controller]")]
[Authorize]
public class DocumentController : ControllerBase
{
    private readonly IDocumentService _documentService;

    public DocumentController(IDocumentService documentService)
    {
        _documentService = documentService;
    }

    [HttpGet]
    public async Task<IActionResult> GetDocuments([FromQuery] int page = 1, [FromQuery] int pageSize = 10, [FromQuery] string? keyword = null)
    {
        try
        {
            var userId = GetCurrentUserId();
            var documents = await _documentService.GetAllDocumentsAsync(userId, page, pageSize, keyword);
            return Ok(documents);
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetDocumentById(Guid id)
    {
        try
        {
            var userId = GetCurrentUserId();
            var document = await _documentService.GetDocumentByIdAsync(userId, id);
            if (document == null)
                return NotFound(new { message = "文档不存在" });
            return Ok(document);
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    [HttpPost("upload")]
    public async Task<IActionResult> UploadDocument([FromForm] IFormFile file, [FromForm] string? fileName = null)
    {
        try
        {
            var userId = GetCurrentUserId();
            var document = await _documentService.UploadDocumentAsync(userId, file, fileName);
            return CreatedAtAction(nameof(GetDocumentById), new { id = document.Id }, document);
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteDocument(Guid id)
    {
        try
        {
            var userId = GetCurrentUserId();
            Console.WriteLine($"用户 {userId} 尝试删除文档 {id}");

            var success = await _documentService.DeleteDocumentAsync(userId, id);
            if (!success)
            {
                Console.WriteLine($"删除文档失败: 服务层返回false");
                return BadRequest(new { message = "删除失败，请重试" });
            }

            Console.WriteLine($"文档 {id} 删除成功");
            return NoContent();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"删除文档时发生异常: {ex.Message}");
            Console.WriteLine($"异常类型: {ex.GetType().Name}");
            Console.WriteLine($"异常堆栈: {ex.StackTrace}");

            // 如果是数据库相关异常，提供更具体的错误信息
            if (ex.InnerException != null)
            {
                Console.WriteLine($"内部异常: {ex.InnerException.Message}");
                return BadRequest(new { message = $"删除失败: {ex.InnerException.Message}" });
            }

            return BadRequest(new { message = $"删除失败: {ex.Message}" });
        }
    }

    [HttpGet("{id}/chunks")]
    public async Task<IActionResult> GetDocumentChunks(Guid id, [FromQuery] int page = 1, [FromQuery] int pageSize = 10)
    {
        try
        {
            var userId = GetCurrentUserId();
            var chunks = await _documentService.GetDocumentChunksAsync(userId, id, page, pageSize);
            return Ok(chunks);
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    [HttpPost("{id}/reindex")]
    public async Task<IActionResult> ReindexDocument(Guid id)
    {
        try
        {
            var userId = GetCurrentUserId();
            var success = await _documentService.ReindexDocumentAsync(userId, id);
            if (!success)
                return NotFound(new { message = "文档不存在" });
            return Ok(new { message = "文档重新索引成功" });
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }



    private Guid GetCurrentUserId()
    {
        var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
        if (userIdClaim == null || !Guid.TryParse(userIdClaim.Value, out var userId))
        {
            throw new UnauthorizedAccessException("无法获取当前用户ID");
        }
        return userId;
    }
}